{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cbb2342e",
   "metadata": {},
   "source": [
    "# 1.百度AI开放平台——通用文字识别OCR（光学字符识别）\n",
    "\n",
    "# 2.学生实践周\n",
    "\n",
    "## 2.1通用文字识别\n",
    "\n",
    "* 在通用文字识别的基础上，提供更高精度的识别服务，支持更多语种识别（丹麦语、荷兰语、马来语、瑞典语、印尼语、波兰语、罗马尼亚语、土耳其语、希腊语、匈牙利语、泰语、越语、阿拉伯语、印地语及部分中国少数民族语言），并将字库从1w+扩展到2w+，能识别所有常用字和大部分生僻字。\n",
    "\n",
    "* 请求示例\n",
    "> HTTP 方法：POST\n",
    "> 请求URL： https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic\n",
    "\n",
    "* 请求参数\n",
    ">1. url参数- token\n",
    "> 2.图片参数-图片文件\n",
    "\n"
   ]
  },
  {
   "cell_type": "raw",
   "id": "ad3d09d1",
   "metadata": {},
   "source": [
    "* 示例代码1：\n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用文字识别（高精度版）\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('[本地文件]', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = '[调用鉴权接口获取的token]'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "raw",
   "id": "84981925",
   "metadata": {},
   "source": [
    "* 示例代码2：\n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('xihu.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':zhichao_AT,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "51b0f662",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.8d15023376281fdce48a8ed12974db8a.315360000.1965126376.282335-25954542', 'expires_in': 2592000, 'session_key': '9mzdDcW2IuEYhS0IcmAGrKdVjRC8hoFPIK5EOCUl/R/xxgWR+1VXJ4yLBpDRttXMMwChmelwzdKRyMYpp/EC0mnTtJkV7A==', 'access_token': '24.63ea53e45f10fc5a3508113f62897da1.2592000.1652358376.282335-25954542', 'scope': 'public vis-ocr_ocr brain_ocr_scope brain_ocr_general brain_ocr_general_basic vis-ocr_business_license brain_ocr_webimage brain_all_scope brain_ocr_idcard brain_ocr_driving_license brain_ocr_vehicle_license vis-ocr_plate_number brain_solution brain_ocr_plate_number brain_ocr_accurate brain_ocr_accurate_basic brain_ocr_receipt brain_ocr_business_license brain_solution_iocr brain_qrcode brain_ocr_handwriting brain_form brain_ocr_passport brain_ocr_vat_invoice brain_numbers brain_ocr_business_card brain_ocr_train_ticket brain_ocr_taxi_receipt vis-ocr_household_register vis-ocr_vis-classify_birth_certificate vis-ocr_台湾通行证 vis-ocr_港澳通行证 vis-ocr_机动车购车发票识别 vis-ocr_机动车检验合格证识别 vis-ocr_车辆vin码识别 vis-ocr_定额发票识别 vis-ocr_保单识别 vis-ocr_机打发票识别 vis-ocr_行程单识别 brain_ocr_vin brain_ocr_quota_invoice brain_ocr_birth_certificate brain_ocr_household_register brain_ocr_HK_Macau_pass brain_ocr_taiwan_pass brain_ocr_vehicle_invoice brain_ocr_vehicle_certificate brain_ocr_air_ticket brain_ocr_invoice brain_ocr_insurance_doc brain_formula brain_seal brain_ocr_facade brain_ocr_meter brain_doc_analysis brain_ocr_webimage_loc brain_ocr_medical_paper brain_ocr_doc_analysis_office brain_vat_invoice_verification brain_ocr_medical_detail brain_vehicle_registration_certificate brain_ocr_online_taxi_itinerary brain_ocr_multi_idcard brain_ocr_mixed_multi_vehicle brain_ocr_weigth_note brain_ocr_ multiple_invoice wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': '0bff5cc4592808aab7db9872d65e7bd6'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "payload = {\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'5HRS6BWnIXfZZYyoCmh8eQMD',\n",
    "    'client_secret':'kPfyBFRYaMj609U3iUMMQlsxHcDFNOdH'\n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "c99b1770",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.63ea53e45f10fc5a3508113f62897da1.2592000.1652358376.282335-25954542'"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_token = response.json()['access_token']\n",
    "my_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "a8bd47fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 封装函数\n",
    "import requests\n",
    "import base64\n",
    "def things(token,image_path,url):\n",
    "    request_url = url\n",
    "    # 二进制方式打开图片文件\n",
    "    f = open(image_path, 'rb')\n",
    "    img = base64.b64encode(f.read())\n",
    "    \n",
    "    params = {\n",
    "        \"image\":img,\n",
    "        \"id_card_side\":\"front\"\n",
    "             }\n",
    "    access_token = token\n",
    "    request_url = request_url + \"?access_token=\" + access_token\n",
    "    headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "    response = requests.post(request_url, data=params, headers=headers)\n",
    "    return response.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "2789c337",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 实践A-1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "169e3acb",
   "metadata": {},
   "source": [
    "## 2.2网络图片文字识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "b4cf3a54",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'words_result': [{'words': '情奥运'}, {'words': '民运动'}],\n",
       " 'words_result_num': 2,\n",
       " 'log_id': 1513856082122238297}"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/webimage\"\n",
    "things(my_token,\"WT.jpg\",url)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "6d75a35e",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 实践A-2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad4c435a",
   "metadata": {},
   "source": [
    "## 2.3手写文字识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "7714d7a7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'words_result': [{'location': {'top': 0,\n",
       "    'left': 0,\n",
       "    'width': 623,\n",
       "    'height': 35},\n",
       "   'words': '0心'},\n",
       "  {'location': {'top': 31, 'left': 148, 'width': 248, 'height': 71},\n",
       "   'words': '说明书'},\n",
       "  {'location': {'top': 70, 'left': 479, 'width': 137, 'height': 59},\n",
       "   'words': '30'},\n",
       "  {'location': {'top': 108, 'left': 0, 'width': 525, 'height': 74},\n",
       "   'words': '①不能让小狗饥饿'},\n",
       "  {'location': {'top': 184, 'left': 0, 'width': 487, 'height': 74},\n",
       "   'words': '②禁止冷暴力小狗'},\n",
       "  {'location': {'top': 253, 'left': 2, 'width': 560, 'height': 75},\n",
       "   'words': '②在小狗悲伤的时候'},\n",
       "  {'location': {'top': 323, 'left': 80, 'width': 408, 'height': 90},\n",
       "   'words': '记得要拥抱对方'},\n",
       "  {'location': {'top': 390, 'left': 62, 'width': 560, 'height': 119},\n",
       "   'words': '3④要一直一直'},\n",
       "  {'location': {'top': 475, 'left': 75, 'width': 547, 'height': 141},\n",
       "   'words': '0爱小狗'},\n",
       "  {'location': {'top': 611, 'left': 426, 'width': 175, 'height': 33},\n",
       "   'words': 'Uo. I. oU '},\n",
       "  {'location': {'top': 658, 'left': 494, 'width': 104, 'height': 63},\n",
       "   'words': '汪!'},\n",
       "  {'location': {'top': 801, 'left': 347, 'width': 274, 'height': 50},\n",
       "   'words': '2030009'}],\n",
       " 'words_result_num': 12,\n",
       " 'log_id': 1513857541605489670}"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting\"\n",
    "things(my_token,\"SXWZ.jpg\",url)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "3bcea828",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 实践A-3"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dad67387",
   "metadata": {},
   "source": [
    "## 2.4二维码识别\n",
    "[草料二维码生成器]https://cli.im/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "1fb81172",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'codes_result': [{'text': ['来个男人'], 'type': 'QR_CODE'}],\n",
       " 'codes_result_num': 1,\n",
       " 'log_id': 1513858699634785669}"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/qrcode\"\n",
    "things(my_token,\"EWM.jpg\",url)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c6c070af",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 实践-4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2072fcf1",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "e0ae7e1c",
   "metadata": {},
   "source": [
    "## 2.5卡片类文字识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "7d0046fc",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 实践-5 身份证&银行卡"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "4a911f16",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'codes_result': [{'text': ['20110210206600'], 'type': 'QR_CODE'}],\n",
       " 'codes_result_num': 1,\n",
       " 'log_id': 1513862068627214795}"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "URL = \" https://aip.baidubce.com/rest/2.0/ocr/v1/idcard\"\n",
    "things(my_token,\"XSZ.jpg\",url)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "733ff4fc",
   "metadata": {},
   "source": [
    "## 财务类文字识别-增值税发票识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "c58157e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 实践-6"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "1dddbf16",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'words_result_num': 43,\n",
       " 'words_result': {'AmountInWords': '贰佰肆拾壹元玖角伍分',\n",
       "  'InvoiceNumConfirm': '',\n",
       "  'CommodityEndDate': [],\n",
       "  'CommodityVehicleType': [],\n",
       "  'CommodityStartDate': [],\n",
       "  'CommodityPrice': [{'row': '1', 'word': '228.254717'}],\n",
       "  'NoteDrawer': '李骏',\n",
       "  'SellerAddress': '上海市长宁区遵义路107号10楼021-62750808',\n",
       "  'CommodityNum': [{'row': '1', 'word': '13.70'}],\n",
       "  'SellerRegisterNum': '913100007421296207',\n",
       "  'MachineCode': '499099774351',\n",
       "  'Remarks': '730632668533',\n",
       "  'SellerBank': '中国工商银行上海市虹桥开发区支行100124271930032769',\n",
       "  'CommodityTaxRate': [{'row': '1', 'word': '6%'}],\n",
       "  'TotalTax': '13.70',\n",
       "  'InvoiceCodeConfirm': '031001600311',\n",
       "  'CheckCode': '01519962196503160071',\n",
       "  'InvoiceCode': '031001600311',\n",
       "  'InvoiceDate': '2017年11月13日',\n",
       "  'PurchaserRegisterNum': '913100005647710460',\n",
       "  'InvoiceTypeOrg': '上海增值税电子普通发票',\n",
       "  'OnlinePay': '',\n",
       "  'Password': '0325<*2*64*6*3<*46*8+3>-08+079-864<458+<8355<07<379*053+1++496+048+829+7-0907+-/883/05304><6-20194/219>/35+395+*',\n",
       "  'Agent': '否',\n",
       "  'AmountInFiguers': '241.95',\n",
       "  'PurchaserBank': '中国银行上海市九江路支行448159231184',\n",
       "  'Checker': '王燕清',\n",
       "  'City': '',\n",
       "  'TotalAmount': '228.25',\n",
       "  'CommodityAmount': [],\n",
       "  'PurchaserName': '洋达国际货运代理(上海)有限公司',\n",
       "  'CommodityType': [{'row': '1', 'word': '228.25'}],\n",
       "  'Province': '上海',\n",
       "  'InvoiceType': '电子普通发票',\n",
       "  'SheetNum': '',\n",
       "  'PurchaserAddress': '台延安东路175号旺角广场205室23279000',\n",
       "  'CommodityTax': [],\n",
       "  'CommodityPlateNum': [],\n",
       "  'CommodityUnit': [{'row': '1', 'word': '1'}],\n",
       "  'Payee': '蒋淼露',\n",
       "  'CommodityName': [{'row': '1', 'word': '快递服务价外费用'}],\n",
       "  'SellerName': '联邦快递(中国)有限公司上海分公司',\n",
       "  'InvoiceNum': '81471594'},\n",
       " 'log_id': 1513862360323167801}"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "url = \" https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice\"\n",
    "things(my_token,\"FP.jpg\",url)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7316bb75",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
